﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MvcShoppingMall.Model;
using System.Web.Mvc;
using System.Web.Routing;
using System.Text;
using System.Web.Mvc.Html;
using MvcShoppingMall.HtmlHelper;

namespace MvcShoppingMall.HtmlHelper
{
    public static class HtmlExtension
    {   
        public static MvcHtmlString Pager<T>(this System.Web.Mvc.HtmlHelper html, PageList<T> data)
        {
            //计算开始数字
            int startNum = data.PageIndex - 3 >= 1 ? data.PageIndex - 3 : 1;
            //计算结束数字
            int endNum = data.TotalPage - startNum > 7 ? startNum + 7 : data.TotalPage;
            //获取路由的 URL 参数值和默认值的集合
            var rotueValues = html.ViewContext.RouteData.Values;
            //合并URL数据
            var querys = html.ViewContext.HttpContext.Request.QueryString;

            foreach (string key in querys)
            {
                if (!string.IsNullOrEmpty(key)) rotueValues[key] = querys[key];
            }
            //合并表单数据
            var forms = html.ViewContext.HttpContext.Request.Form;
            foreach (string key in forms)
            {
                if (!string.IsNullOrEmpty(key)) rotueValues[key] = forms[key];
            }
            //用于拼接a标签
            var linkTag = new StringBuilder();
            //动作方法名称
            var actionName = rotueValues["action"].ToString();
            //控制上一页和首页按钮的生成
            if (data.HasPreviousPage)
            {
                rotueValues["pageIndex"] = 1;
                linkTag.AppendFormat("<li>{0}</li>", html.ActionLink("首页", actionName, rotueValues));
                rotueValues["pageIndex"] = data.PageIndex - 1;
                linkTag.AppendFormat("<li>{0}</li>", html.ActionLink("上一页", actionName, rotueValues));
            }
            //输出数字页
            for (int i = startNum; i < endNum; i++)
            {
                rotueValues["pageIndex"] = i;
                if (data.PageIndex == i)
                {
                    linkTag.AppendFormat("<li class='active'>{0}</li>", html.ActionLink(i.ToString(), actionName, rotueValues));
                }
                else
                {
                    linkTag.AppendFormat("<li>{0}</li>", html.ActionLink(i.ToString(), actionName, rotueValues));
                }

            }
            //控制尾页下一页
            if (data.HasNextPage)
            {
                rotueValues["pageIndex"] = data.PageIndex + 1;
                linkTag.AppendFormat(" <li>{0}</li>", html.ActionLink("下一页", actionName, rotueValues));
                rotueValues["pageIndex"] = data.TotalPage;
                linkTag.AppendFormat(" <li>{0}</li>", html.ActionLink("尾页", actionName, rotueValues));
            }

            return MvcHtmlString.Create(linkTag.ToString());
        }
    }
}